package com.qifan.energy.activity;

import androidx.annotation.RequiresApi;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.qifan.energy.base.BaseActivity;
import com.qifan.energy.R;
import com.qifan.energy.global.Constant;
import com.qifan.energy.global.Keys;
import com.qifan.energy.widget.CustomTitleBar;

import butterknife.BindView;

public class WebsiteActivity extends BaseActivity {

    @BindView(R.id.website)
    WebView webView;
    private String titText;
    private String url;
    private boolean isAutoTitle;
    private CustomTitleBar titleBar;

    /*@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }*/

    @Override
    protected int getLayoutId() {
        return R.layout.activity_website;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        //获取UI
        titleBar = (CustomTitleBar)findViewById(R.id.title_layout_bar);

        initSettings();
        Bundle params = getIntent().getExtras();
        if (params != null){
            isAutoTitle = params.getBoolean(Keys.AUTO_TITLE, false);
            titText = params.getString(Keys.TITLE, getString(R.string.app_name));
            url = params.getString(Keys.URL, Constant.BaseUrl8085);
        }
        webView.loadUrl(url);
    }

    @Override
    protected void initData() {

    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initSettings() {
        WebSettings settings = webView.getSettings();
        //水平不显示
        webView.setHorizontalScrollBarEnabled(false);
        //垂直不显示
        webView.setVerticalScrollBarEnabled(false);
        //支持JS
        settings.setJavaScriptEnabled(true);
        //自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);//设置true,才能让Webivew支持<meta>标签的viewport属性
        settings.setDomStorageEnabled(true);
        /*settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);*/
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setAllowContentAccess(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAppCacheEnabled(true);
        // 允许使用数据库
        settings.setDatabaseEnabled(true);
        settings.setGeolocationEnabled(true);
        String dir = getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setGeolocationDatabasePath(dir);
        settings.setDomStorageEnabled(true);
        // 设置可以支持缩放
        settings.setSupportZoom(true);
        // 设置出现缩放工具
        settings.setBuiltInZoomControls(false);
        //设定缩放控件隐藏
        settings.setDisplayZoomControls(false);
        //扩大比例的缩放
        /*settings.setUseWideViewPort(true);*/
        //webView.setInitialScale(100);  //代表不缩放
        settings.setTextZoom(100);
        webView.setWebViewClient(webViewClient);
        webView.setWebChromeClient(webChromeClient);
        //H5交互
        /*webView.addJavascriptObject(new JsApi(this), null);*/
        // 自行实现下载服务
        /*webView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            whenDownload(url);
        });*/
    }

    WebViewClient webViewClient = new WebViewClient(){

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //return super.shouldOverrideUrlLoading(view, url);
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                /*注意：super句话一定要删除，或者注释掉，否则又走handler.cancel() 默认的不支持https的了。
                super.onReceivedSslError(view, handler, error);*/
            handler.proceed();// 接受所有网站的证书
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    };

    WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (isAutoTitle) {
                titText = title;
                titleBar.setTitleBarTitle(title);
            }
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            if (!PermissionUtils.isGranted(PermissionConstants.LOCATION)) {
                PermissionUtils.permission(PermissionConstants.LOCATION).callback(new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        callback.invoke(origin, true, false);
                    }

                    @Override
                    public void onDenied() {

                    }
                }).request();
            } else {
                callback.invoke(origin, true, false);
            }
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.setVisibility(View.GONE);
            webView.loadUrl("about:blank");
            webView.stopLoading();
            webView.setWebChromeClient(null);
            webView.setWebViewClient(null);
            webView.destroy();
            webView = null;
        }
    }
}
